<template>
  <div class="server-create p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">添加服务器</h2>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="max-w-3xl"
      >
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="formData.ip" placeholder="请输入IP地址" />
        </el-form-item>

        <el-form-item label="主机名" prop="hostname">
          <el-input v-model="formData.hostname" placeholder="请输入主机名" />
        </el-form-item>

        <el-form-item label="产品线" prop="product_line">
          <el-input v-model="formData.product_line" placeholder="请输入产品线" />
        </el-form-item>

        <el-form-item label="服务器类型" prop="server_type">
          <el-select v-model="formData.server_type" placeholder="请选择服务器类型" class="w-full">
            <el-option label="Web服务器" :value="ServerType.WEB" />
            <el-option label="数据库服务器" :value="ServerType.DATABASE" />
            <el-option label="应用服务器" :value="ServerType.APPLICATION" />
            <el-option label="文件服务器" :value="ServerType.FILE" />
            <el-option label="缓存服务器" :value="ServerType.CACHE" />
            <el-option label="代理服务器" :value="ServerType.PROXY" />
            <el-option label="其他" :value="ServerType.OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item label="服务器状态" prop="server_status">
          <el-select v-model="formData.server_status" placeholder="请选择服务器状态" class="w-full">
            <el-option label="在线" :value="ServerStatus.ONLINE" />
            <el-option label="离线" :value="ServerStatus.OFFLINE" />
            <el-option label="维护中" :value="ServerStatus.MAINTENANCE" />
            <el-option label="已退役" :value="ServerStatus.DECOMMISSIONED" />
          </el-select>
        </el-form-item>

        <el-form-item label="使用状态" prop="usage_status">
          <el-select v-model="formData.usage_status" placeholder="请选择使用状态" class="w-full">
            <el-option label="使用中" :value="ServerUsageStatus.IN_USE" />
            <el-option label="可用" :value="ServerUsageStatus.AVAILABLE" />
            <el-option label="已预留" :value="ServerUsageStatus.RESERVED" />
            <el-option label="已报废" :value="ServerUsageStatus.RETIRED" />
          </el-select>
        </el-form-item>

        <el-form-item label="环境" prop="environment">
          <el-select v-model="formData.environment" placeholder="请选择服务器环境" class="w-full">
            <el-option label="测试环境" :value="ServerEnvironment.TESTING" />
            <el-option label="开发环境" :value="ServerEnvironment.DEVELOPMENT" />
            <el-option label="线上环境" :value="ServerEnvironment.PRODUCTION" />
          </el-select>
        </el-form-item>

        <el-form-item label="序列号" prop="sn">
          <el-input v-model="formData.sn" placeholder="请输入序列号（可选）" />
        </el-form-item>

        <el-form-item label="机柜位置" prop="rack_location">
          <el-input v-model="formData.rack_location" placeholder="请输入机柜位置（可选）" />
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="formData.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注（可选）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ServerCreate">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { createServer } from '@/request/server-api'
import { ServerType, ServerStatus, ServerUsageStatus, ServerEnvironment } from '@/model/server-model'
import type { ServerCreateRequest } from '@/model/server-model'

// 路由对象
const router = useRouter()

// 表单引用
const formRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 表单数据
const formData = reactive<ServerCreateRequest>({
  ip: '',
  hostname: '',
  product_line: '',
  server_type: ServerType.WEB,
  server_status: ServerStatus.ONLINE,
  usage_status: ServerUsageStatus.AVAILABLE,
  environment: undefined,
  sn: '',
  rack_location: '',
  notes: ''
})

// 表单验证规则
const formRules = reactive<FormRules>({
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: 'IP地址格式不正确', trigger: 'blur' }
  ],
  hostname: [
    { required: true, message: '请输入主机名', trigger: 'blur' },
    { min: 2, max: 50, message: '主机名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  server_type: [
    { required: true, message: '请选择服务器类型', trigger: 'change' }
  ],
  server_status: [
    { required: true, message: '请选择服务器状态', trigger: 'change' }
  ],
  usage_status: [
    { required: true, message: '请选择使用状态', trigger: 'change' }
  ],
  environment: [
    { required: false, message: '请选择服务器环境', trigger: 'change' }
  ]
})

/**
 * 提交表单
 */
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请正确填写表单信息')
      return
    }
    
    loading.value = true
    try {
      const response = await createServer(formData)
      
      if (response.code === 0) {
        ElMessage.success('添加服务器成功')
        router.push('/server/list')
      } else {
        ElMessage.error(response.errorMsg || '添加服务器失败')
      }
    } catch (error) {
      console.error('添加服务器失败:', error)
      ElMessage.error('添加服务器失败')
    } finally {
      loading.value = false
    }
  })
}

/**
 * 重置表单
 */
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

/**
 * 返回列表页
 */
const goBack = () => {
  router.push('/server/list')
}
</script>
